﻿using System.Data.Entity;

namespace Altairis.FluffyCloud.Data {

    public class FluffyDbContext : DbContext {

        public FluffyDbContext() : base("FluffyDbContext") { }

        public DbSet<Message> Messages { get; set; }

        public DbSet<Role> Roles { get; set; }

        public DbSet<TopicAclEntry> TopicAclEntries { get; set; }

        public DbSet<TopicCategory> TopicCategories { get; set; }

        public DbSet<TopicPost> TopicPosts { get; set; }

        public DbSet<Topic> Topics { get; set; }

        public DbSet<TopicUserState> TopicUserStates { get; set; }

        public DbSet<UserAclEntry> UserAclEntries { get; set; }

        public DbSet<User> Users { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder) {

            // Mapping required by providers
            modelBuilder.Entity<User>()
                .HasMany(u => u.Roles)
                .WithMany(r => r.Users)
                .Map(m => {
                    m.ToTable("RoleMemberships");
                    m.MapLeftKey("UserName");
                    m.MapRightKey("RoleName");
                });

            // Mapping for private messages subsystem
            modelBuilder.Entity<User>()
                .HasMany(u => u.MessagesSent)
                .WithRequired(m => m.FromUser)
                .HasForeignKey(m => m.FromUserName);
            modelBuilder.Entity<User>()
                .HasMany(u => u.MessagesReceived)
                .WithRequired(m => m.ToUser)
                .HasForeignKey(m => m.ToUserName);
        }
    }
}